package cn.juforg.gobang.listener;

import android.util.FloatMath;
import android.util.Log;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import cn.juforg.gobang.ChessBoard;
import cn.juforg.gobang.ZoomPoint;
import cn.juforg.gobang.interfaces.ChessBoardImpl;

public class ChessboardGestureListener extends SimpleOnGestureListener{
	private ChessBoard chessBoard;
	private float orgDistance ,lastDistance;
	
	private float zoomRatio;// 缩放比例
	
	public ChessboardGestureListener(ChessBoard chessBoard) {
		this.chessBoard = chessBoard;
	}

	@Override
	public boolean onDown(MotionEvent e) {
		Log.d("gesture list", "x1" + e.getX(0));
		return super.onDown(e);
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		Log.d("gesture list", "velocityX:" + velocityX+"velocityY"+velocityY);
		return super.onFling(e1, e2, velocityX, velocityY);
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		orgDistance = getTwoPointDistance(e1);
		lastDistance = getTwoPointDistance(e2);
		Log.d("gesture list", "orgDis:" + orgDistance);
		if ( Math.abs(orgDistance-lastDistance) >1) {
			zoomRatio = lastDistance / orgDistance;
			generateMidPoint(e2);
			chessBoard.zoomChessBoard(zoomRatio);
			return true;
		}
		return super.onScroll(e1, e2, distanceX, distanceY);
	}
	
	private float getTwoPointDistance(MotionEvent event) {
	    float x = event.getX(0) - event.getX(1);
	    float y = event.getY(0) - event.getY(1);
	    return FloatMath.sqrt(x * x + y * y);
	}  
	
	//计算中点位置 
    private void generateMidPoint(MotionEvent event) {
    	float x = event.getX(0) + event.getX(1); 
    	float y = event.getY(0) + event.getY(1); 
    	ZoomPoint.getInstance().set(x / 2, y / 2); 
    	ChessBoard.zoomChess = ChessBoardImpl.generateChess(x / 2, y / 2);
    	Log.d("gesture listener", ZoomPoint.getInstance().toString());
   }

}
